<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/20
 * Time: 11:46
 */

namespace app\queue\oceanengine;

use app\common\lib\Common;
use app\common\lib\Guzzle;
use app\common\lib\Puppeteer;
use app\common\lib\RedisQueue;
use app\common\lib\TencentAsr;
use app\common\lib\TencentIvld;
use app\exception\IndexException;
use app\logic\index\novel\OceanengineLogic;
use app\model\redis\RedisQueueModel;
use app\model\user\UserModel;
use app\model\user\UserPromotionVideoModel;
use app\model\video\AsyncUploadVideoIvldModel;
use support\Cache;
use Webman\RedisQueue\Consumer;
use app\common\lib\TencentCos;

class Oceanengine  implements Consumer
{
    // 要消费的队列名
    public $queue = 'oceanengineAttribution';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    protected $resultData = [];

    // 消费
    public function consume($data)
    {
        Common::initQueueConfig();

        $queue            = RedisQueueModel::getInstance()->find($data['queueid']);
        $queue->exec_time = date('Y-m-d H:i:s');
        $queue->save();

        try {

            $result = $this->handle($data);

            RedisQueue::getInstance()->saveQueue($this->queue, $data, $result);
        } catch (\Throwable $e) {
            RedisQueue::getInstance()->saveQueue($this->queue, $data, ['error' => $e->getMessage()]);
            Common::queueExecptionReport($queue, $data, $e);
        }
    }

    protected function handle($data)
    {
        $user = UserModel::getInstance()->getWhere(['user_sn' => $data['user_sn']])->first();
        if ($user == false) {
            return ['empty'];
        }
        if ($data['type'] == 'active') {
            //激活回传
            return $this->activeEvent($data,$user);
        }elseif ($data['type'] == 'register') {
            //注册回传
            return $this->registerEvent($data,$user);
        }elseif ($data['type'] == 'pay') {
            //付费回传
            return $this->payEvent($data,$user);
        }

        return ['success'];
    }

    protected function activeEvent($data,$user)
    {
        $first = UserModel::getInstance()->getWhere(['device_number' => $data['device']])->orderBy('created_at', 'asc')->first();

        if ($first && $first['user_sn'] != $user['user_sn']) {
            return ['user_sn existed'];
        } elseif (!empty($first['callback_param'])) {
            return ['callback_param existed'];
        } elseif (strtotime($first['created_at']) < (time() - 300)) {
            return ['created_at < 5 min'];
        }

        //获取实时归因数据
        $n = 1;
        while (true) {
            $result = \app\common\lib\Oceanengine::getInstance()->getOceanengineAdAttribution($data['platform'], $data['device']);
            if ($result) {
                $result['platform'] = $data['platform'];
                OceanengineLogic::getInstance()->autoCreateTableAndInsertData(
                    [
                        'table'      => 'video_oceanengine_ad_attribution_data',
                        'keyid'      => 'id',
                        'attributes' => $result,
                    ]
                );
                if (!empty($result['callback_param'])) {
                    //直接激活回传，测试先这样
                    //$res = Common::curlApi($result['callback_url'],false);
                    $device = [
                        'platform' => strtolower($data['platform']),
                    ];
                    strtolower($data['platform']) == 'ios' && $device['idfv'] = $data['device'];
                    strtolower($data['platform']) == 'android' && $device['android_id'] = $data['device'];
                    $res = \app\common\lib\Oceanengine::getInstance()->submitConversion('active', $result['callback_param'], $device);
                    file_put_contents(runtime_path('oceanengine_conversion.log'), date('Y-m-d H:i:s') . ': active'."\n" . $user['callback_param'] . "\n" . json_encode($res, 256) . "\n\n", 8);


                    $user->callback_param = $result['callback_param'];
                    $user->save();
                    break;
                }
                if ($n > 6) {
                    break;
                }
                $n++;
                sleep(1);
            } else {
                break;
            }
        }

        return ['success'];
    }

    protected function registerEvent($data,$user)
    {
        if (!empty($user['callback_param'])) {
            //直接激活回传，测试先这样
            //$res = Common::curlApi($result['callback_url'],false);
            $device = [
                'platform' => strtolower($data['platform']),
            ];
            strtolower($data['platform']) == 'ios' && $device['idfv'] = $data['device'];
            strtolower($data['platform']) == 'android' && $device['android_id'] = $data['device'];
            $res = \app\common\lib\Oceanengine::getInstance()->submitConversion('active_register', $user['callback_param'], $device);
            file_put_contents(runtime_path('oceanengine_conversion.log'), date('Y-m-d H:i:s') . ': register'."\n" . $user['callback_param'] . "\n" . json_encode($res, 256) . "\n\n", 8);
        }

        return ['success'];
    }

    protected function payEvent($data,$user)
    {
        if (!empty($user['callback_param'])) {
            //直接激活回传，测试先这样
            $device = [];
            if(strlen($user['device_number'])==16){
                $device = [
                    'platform' => 'android',
                    'android_id' => $user['device_number'],
                ];
            }elseif(count(explode('-',$user['device_number']))==5){
                $device = [
                    'platform' => 'ios',
                    'idfv' => $user['device_number'],
                ];
            }
            $properties = [
                'pay_amount'=>round($data['amount']*100)
            ];
            $res = \app\common\lib\Oceanengine::getInstance()->submitConversion('active_pay', $user['callback_param'], $device,$properties);
            file_put_contents(runtime_path('oceanengine_conversion.log'), date('Y-m-d H:i:s') . ': pay'."\n" . $user['callback_param'] . "\n" . json_encode($res, 256) . "\n\n", 8);
        }

        return ['success'];
    }

    // 消费失败回调
    /*
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */
    public function onConsumeFailure(\Throwable $e, $package)
    {
//        echo "consume failure\n";
//        echo $e->getMessage() . "\n";
//        // 无需反序列化
//        var_export($package);

        RedisQueue::getInstance()->saveQueue($this->queue,$package['data'],['error'=>$e->getMessage()]);
    }

}